package cn.tedu.shoppingmall.controller;

import cn.tedu.shoppingmall.mapper.CommodityMapper;
import cn.tedu.shoppingmall.mapper.ShopMapper;
import cn.tedu.shoppingmall.mapper.TransactionMapper;
import cn.tedu.shoppingmall.mapper.UserMapper;
import cn.tedu.shoppingmall.vo.*;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

@Api(tags = "2结算模块")
@RestController
@RequestMapping("/shopping")
public class ShoppingController {
    @Autowired
    CommodityMapper commodityMapper;
    @Autowired
    TransactionMapper transactionMapper;
    @Autowired
    UserMapper userMapper;
    @Autowired
    ShopMapper shopMapper;


    //单个商品直接买
    @GetMapping("/pay")
    @Transactional  //添加事务
    public String pay(int id, int num, @AuthenticationPrincipal UserDetails user){
        //商品购买次数加一
        commodityMapper.UpdateToCommodityPaynumAdd(id);
        Commodity com = commodityMapper.SelectById(id);
        if (com==null) {
            return "该商品已下架!";//若果没查到,证明没有该商品
        }
        int sum = commodityMapper.SelectToSum(id).getSum();
        int sales = commodityMapper.SelectToSum(id).getSalesnum();
        if (sum-sales-num < 0){
            return "购买失败,商品库存不足!";
        }else {
            commodityMapper.toShopping(id,num);
            User u = userMapper.selectByUsername(user.getUsername());
            Transaction transaction = new Transaction();
            transaction.setState(1);  //状态可见
            transaction.setUserid(u.getId());
            transaction.setUsername(u.getUsername());
            LocalDateTime created = LocalDateTime.now().withNano(0);
            transaction.setCreated(created);
            transaction.setComsum(num);
            //代替id成唯一标识
            String uuid = UUID.randomUUID().toString();
            transaction.setUUID(uuid);
            transaction.setPrice(
                   com.getPrice()*num
            );
            transactionMapper.payShopCar(transaction);
            //给comtrans赋值
            ComTrans comTrans = new ComTrans();
            comTrans.setName(com.getName());
            comTrans.setIntro(com.getIntro());
            comTrans.setSum(num);
            comTrans.setPrice(com.getPrice());
            comTrans.setClassId(com.getClassId());
            comTrans.setComId(id);
            comTrans.setUrl(com.getUrl());
            comTrans.setTransUUID(uuid);
            transactionMapper.payShopCarToComtrans(comTrans);
            //查询用户所购买过的所有订单金额及商品数量,分别赋值---调用下边方法
            UpdateUserPriceAndSum(user.getUsername());
            return "购买成功!";
        }

    }
    //购物车结算价格
    @GetMapping("/pays/priceAll")
    public Double paysPriceAll(int[] comIds){
        Double priceAll = 0.00;
        for (int i : comIds){
            Shopcar shopcar = shopMapper.SelectShopcarById(i);
            //计算价格
            priceAll += shopcar.getSum()*shopcar.getPrice();
        }
        return priceAll;
    }
    //购物车结算
    @PostMapping("/pays")
    @Transactional  //添加事务
    public String pays(int[] comIds,@AuthenticationPrincipal UserDetails user){
        if (user!=null){
            if (paysPriceAll(comIds)<=0){
                return "没有选择商品,结算失败!";
            }
            User u = userMapper.selectByUsername(user.getUsername());
            Transaction transaction = new Transaction();
            transaction.setState(1);  //状态可见
            transaction.setUserid(u.getId());
            transaction.setUsername(u.getUsername());
            LocalDateTime created = LocalDateTime.now().withNano(0);
            //代替id成唯一标识
            String uuid = UUID.randomUUID().toString();
            transaction.setUUID(uuid);
            transaction.setCreated(created);
            //调用上边的总价方法
            transaction.setPrice(
                    paysPriceAll(comIds)
            );
            //把transactionde comsum赋值
            transactionMapper.payShopCar(transaction);
            int transactionId = transactionMapper.getTransactionIdByUuid(uuid);

//            int id = transaction.getId();
//            System.out.println("ididididididdi"+id);

            //遍历得到商品信息插入comtrans表
            List<Integer> comids = new ArrayList<>();
            List<Integer> comsums = new ArrayList<>();
            for (int i : comIds){


               Shopcar shopcar = shopMapper.SelectShopcarById(i);
                //商品购买次数加一
                commodityMapper.UpdateToCommodityPaynumAdd(shopcar.getComid());

               comids.add(shopcar.getComid());
               comsums.add(shopcar.getSum());
                ComTrans comTrans = new ComTrans();
                comTrans.setName(shopcar.getName());
                comTrans.setIntro(shopcar.getIntro());
                comTrans.setSum(shopcar.getSum());
                comTrans.setPrice(shopcar.getPrice());
                comTrans.setClassId(shopcar.getClassId());
                comTrans.setComId(shopcar.getComid());
                comTrans.setUrl(shopcar.getUrl());
                comTrans.setTransUUID(uuid);

                //增删com表的库存
                Commodity commodity = commodityMapper.SelectToSum(shopcar.getComid());
                int sums = commodity.getSum();
                int sales = commodity.getSalesnum();
                if (sums-sales-shopcar.getSum() < 0){
                    return "购买失败,商品库存不足!";
                }else {
                    commodityMapper.toShopping(shopcar.getComid(),shopcar.getSum());
                }

               transactionMapper.payShopCarToComtrans(comTrans);
                shopMapper.deleteShopcarOne(i);
            }
            int sum = transactionMapper.getComTransCountByTransactionUUID(uuid);
            transaction.setComsum(sum);
            //改comsum
            transactionMapper.updateTransactionComsum(transactionId,sum);

//            transaction.setComid(comids.toString());  //暂时没用
//            transaction.setComsum(comsums.toString());  //暂时没用

            //查询用户所购买过的所有订单金额及商品数量,分别赋值---调用下边方法
            UpdateUserPriceAndSum(user.getUsername());

            return "ok";

        }
        return "用户没登录!";
    }


    //更新用户price和sum的方法
    public UserDetail UpdateUserPriceAndSum(String username){
        UserDetail userDetail = userMapper.findUserDetailByUserUsername(username);
        userDetail.setSum(transactionMapper.getTransComsumByUsername(username));
        userDetail.setPrice(transactionMapper.getTransPriceByUsername(username));
        userMapper.UpdateUserPriceAndSum(userDetail);
        return userDetail;
    }
}
